﻿var virualpath = "../../";
var prourlid = 0;
var AdminName = "";
var Password = "";
var proid = 0;
$(function () {
    
    var res = window.location.search;
    var resdata = res.split(",")
    if (res == "") {
        location.href = "index.html"
    } else {
        if (resdata.length <= 2) {
            prourlid = resdata[0].split("=")[1];
            proid = resdata[1].split("=")[1];
        } else {
            prourlid = resdata[0].split("=")[1];
            AdminName = resdata[1].split("=")[1];
            Password = resdata[2].split("Pwd=")[1];
        }
        var second = 0;
        window.setInterval(function () {
            second++;
        }, 1000);
        var tjArr = localStorage.getItem("jsArr") ? localStorage.getItem("jsArr") : '[{}]';
        $.cookie('tjRefer', getReferrer(), { expires: 1, path: '/' });
        window.onbeforeunload = function () {
         
         
            if ($.cookie('tjRefer') == '') {
                var tjT = eval('(' + localStorage.getItem("jsArr") + ')');
                if (tjT) {
                    tjT[tjT.length - 1].time += second;
                    var jsArr = JSON.stringify(tjT);
                    localStorage.setItem("jsArr", jsArr);
                }
            } else {

                var tjArr = localStorage.getItem("jsArr") ? localStorage.getItem("jsArr") : '[{}]';
                var dataArr = {
                    'CoreseId': prourlid,
                    'AdminId': sessionStorage.getItem("AdminId"),
                    'url': location.href,
                    'time': second,
                    'refer': getReferrer(),
                    'timeIn': new Date(+new Date() + 8 * 3600 * 1000 - (second * 1000)).toJSON().substr(0, 19).replace("T", " "),
                    'timeOut': new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", " "),
                };
                tjArr = eval('(' + tjArr + ')');
                tjArr.push(dataArr);
                tjArr = JSON.stringify(tjArr);
                localStorage.setItem("jsArr", tjArr);

            }
            var list = JSON.parse(localStorage.getItem("jsArr"));
            console.log(list)
            var obj = {};
            obj.AdminId = list[list.length - 1].AdminId;
            obj.ResourceId = list[list.length - 1].CoreseId;
            obj.StartTime = list[list.length - 1].timeIn;
            obj.EndTime = list[list.length - 1].timeOut;
          
            setTimeout(function () {
                $.ajax({
                    url: virualpath + '/Course/InsertCourseBrowseInfo',
                    type: 'post',
                    data: JSON.stringify(obj),
                    async: false,
                    dataType: 'json',
                    contentType: 'application/json',
                    success: function (data) {
                    }
                })
            }, 0);
            console.log(obj)
        };
        function getReferrer() {
            var referrer = '';
            try {
                referrer = window.top.document.referrer;
            } catch (e) {
                if (window.parent) {
                    try {
                        referrer = window.parent.document.referrer;
                    } catch (e2) {
                        referrer = '';
                    }
                }
            }
            if (referrer === '') {
                referrer = document.referrer;
            }
          console.log(referrer);
       
    }
    $.ajax({
        url: virualpath + '/Session/GetSessionAsync',
        type: 'get',
        async: true,
        contentType: 'application/json',
        success: function (data) {
            var res = JSON.parse(data);
            if (res != undefined) {
                GetCourseinfo(prourlid);
                sessionStorage.setItem("AdminName", res.AdminName)
                sessionStorage.setItem("Pwd", res.EncryptPwd)
            } else {
                if (AdminName != "" && Password != "") {
                    var field = {};
                    field.AdminName = AdminName;
                    field.EncryptPwd = Password;
                    $.ajax({
                        url: virualpath + '/Login/LocationSignIn',
                        type: 'post',
                        dataType: 'json',
                        data: JSON.stringify(field),
                        contentType: 'application/json',
                        async: true,
                        success: function (data) {
                            if (data.RspCode == 1) {
                                GetCourseinfo(prourlid);
                            }
                            if (data.RspCode == 0) {
                                location.href = "index.html"
                            }

                        }
                    })
                } else {
                    alert("请先登录")
                    location.href = "login.html";
                }
            }
        }
    });
    if (sessionStorage.getItem("AdminId") == 1) {
        $("#daochu").show();
    } else {
        $("#daochu").hide();
      
    }
    }
});



//获取课程信息
function GetCourseinfo(id) {
    var obj = {};
    obj.Id = id;
    $.ajax({
        url: virualpath + '/Course/GetByIdCourseInfo',
        type: 'get',
        data: obj,
        async: true,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            var resultData = data;
            if (resultData != undefined) {
                var hrefstr = ""
                if (resultData.MLSLabUrl != null) {
                    hrefstr = "" + resultData.MLSLabUrl + '?/AdminName=' + sessionStorage.getItem("AdminName") + ',Pwd=' + sessionStorage.getItem("Pwd") + "";
                }
                var TopStr = "";
                //TopStr += '<div class="video"><video id="playVideo" onplaying="coursepaly()"  width="880" height="495" poster="' + resultData.Course_Filepath + resultData.Course_VideoImg + '" controls="controls"><source src="' + resultData.Course_Filepath + resultData.Course_VideoUrl + '" type="video/mp4"><p>您的浏览器版本过低，请使用IE9.0或更高版本的浏览器。</p></video><div class="btnvideo"><a href="#" class="cgal" onClick="show()"><img src="images/open.png" width="18px; "></a></div><div id="playTips" class="playTips" onclick="playPause(0)"></div></div><div class="mask" style="display: none; " id="mask"></div><div id="pop_div" class="pop_box"><div class="p_head"><div class="p_h_title"><video id="playVideo" onclick="playPause(1)" width="1160" height="653" poster="' + resultData.Course_Filepath + resultData.Course_VideoImg + '"><source src="' + resultData.Course_Filepath + resultData.Course_VideoUrl + '" type="video/mp4" /><p>您的浏览器版本过低，请使用IE9.0或更高版本的浏览器。</p></video></div><div><a class="p_h_x" onclick="hideDiv(pop_div)" title="关闭窗口"></a></div><div id="playTip_p" class="playTip_p" onclick="playPause(1)"></div></div></div><div class="oth"><div class="anchor"><div class="oneanchor"><a href="#t1">知识点教案</a></div><div class="oneanchor"><a href="#t2">教学演示稿</a></div><div class="oneanchor"><a href="#t3">学习讨论</a></div><div class="oneanchor"><a href="../MLSMooc/NewFolder1/Exam.html?/id=' + id + '">测试习题</a></div><div class="oneanchor"><a href="' + hrefstr + '">进入实验室</a></div><div class="oneanchor"><a href="../MLSMooc/ExamInfo.html?/uid=' + sessionStorage.getItem("AdminId") + ',cid=' + id + '">查看个人成绩</a></div></div><div class="pointoth"><p class="time"><b></b><span>' + resultData.Course_Videomin + '</span></p><p class="recom"><a></a><span>' + resultData.Course_LikeNumber + '喜欢</span></p><p class="browse"><b></b><span>' + resultData.Course_BrowseNumber + '浏览</span></p><p class="comm"><b></b><span>' + resultData.Course_CommentNumber + '讨论</span></p></div></div>';
                TopStr += '<div class="video"><video onplaying="coursepaly()"  poster="' + resultData.Course_Filepath + resultData.Course_VideoImg + '" width="100%" height="100%" controls="controls"><source src="' + resultData.Course_Filepath + resultData.Course_VideoUrl + '" type="video/mp4"></video></div><div class="oth"><div class="anchor"><div class="oneanchor"><a href="#t1">知识点教案</a></div><div class="oneanchor"><a href="#t2">教学演示稿</a></div><div class="oneanchor"><a href="#t3">学习讨论</a></div><div class="oneanchor"><a href="../MLSMooc/NewFolder1/Exam.html?/id=' + id + '">测试习题</a></div><div class="oneanchor"><a href="' + hrefstr + '">进入实验室</a></div><div class="oneanchor"><a href="../MLSMooc/ExamInfo.html?/uid=' + sessionStorage.getItem("AdminId") + ',cid=' + id + '">查看个人成绩</a></div><div class="oneanchor" id="tkxzt"><a href="#" onclick="updateTkxzt('+id+')">编辑弹框选择题</a></div></div><div class="pointoth"><p class="time"><b></b><span>' + resultData.Course_Videomin + '</span></p><p class="recom"><a></a><span>' + resultData.Course_LikeNumber + '喜欢</span></p><p class="browse"><b></b><span>' + resultData.Course_BrowseNumber + '浏览</span></p><p class="comm"><b></b><span>' + resultData.Course_CommentNumber + '讨论</span></p></div></div>';

                $("#Top").append(TopStr);
                if (sessionStorage.getItem("AdminId") == 1) {
                   
                    $("#tkxzt").show();

                } else {
                  
                    $("#tkxzt").hide();
                   
                }
                $("#CourseNameTitle").text(resultData.Course_Name);
                $("#title").text(resultData.Course_Name);
                $("#Content").append(resultData.Course_Content);
                $("a.media").attr("href", "" + resultData.Course_Filepath + resultData.Course_Presentation + "");
                $('a.media').media({ width: 800, height: 650 });
                $('a.mediase').media({ width: 800, height: 650 });
                var caidan = '  <ul class="navi"><li class="one"><a href="Project.html?id=' + resultData.ProId + '">' + resultData.PName + '<span id="ProjectNameTitle"></span></a></li><li class="two"><a href="Course.html?id=' + id + '">' + resultData.Course_Name + '<span id="CourseNameTitle"></span></a></li></ul>'
                $("#caidan").append(caidan)
                GetDiscussionList(resultData.Id);
                GetTextBooks(resultData.Course_Textbooks)
                GetBooks(resultData.Course_Books)
                GetWebsites(resultData.Course_Websites)
            }
        }
    })
}

//获取讨论及回复内容
function GetDiscussionList(id) {
    var resultData = undefined;
    var ReplyresultData = undefined;
    var obj = {};
    obj.id = id;
    $.ajax({
        url: virualpath + '/Discussion/GetByIdDiscussionList',
        type: 'get',
        data: obj,
        async: false,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            resultData = data;
        }
    })
    $.ajax({
        url: virualpath + '/Discussion/GetDiscussionReplyList',
        type: 'get',
        dataType: 'json',
        async: false,
        contentType: 'application/json',
        success: function (data) {
            ReplyresultData = data;
        }
    })
    setTimeout(function () {
        var Str = "";
        if (resultData != undefined && ReplyresultData != undefined) {
            for (var i = 0; i < Object.keys(resultData).length; i++) {
                if (i > 5) {
                    Str += ' <div id="Dishidden" class="onelist" style="display:none"><div class="info"><span class="name">' + resultData[i].LinkName + '' + resultData[i].RoleName + '</span><span class="time">（' + resultData[i].CreateTime + '）</span></div><div class="cont">' + resultData[i].mcdContent + '</div><div class="btn_box"><a class="btn_blu_m2" href="#t3" onclick="ReplyShow(' + resultData[i].mcdId + ',' + resultData[i].aId + ')" >回复</a>&nbsp;&nbsp;<a class="btn_blu_m2"  onclick="DeleteDiscussion(' + resultData[i].mcdId + ',' + resultData[i].aId + ')" >删除</a></div> </div>';
                } else {
                    Str += ' <div class="onelist"><div class="info"><span class="name">' + resultData[i].LinkName + '' + resultData[i].RoleName + '</span><span class="time">（' + resultData[i].CreateTime + '）</span></div><div class="cont">' + resultData[i].mcdContent + '</div><div class="btn_box"><a class="btn_blu_m2" href="#t3" onclick="ReplyShow(' + resultData[i].mcdId + ',' + resultData[i].aId + ')" >回复</a>&nbsp;&nbsp;<a class="btn_blu_m2"  onclick="DeleteDiscussion(' + resultData[i].mcdId + ',' + resultData[i].aId + ')" >删除</a></div> </div>';
                }
                for (var j = 0; j < Object.keys(ReplyresultData).length; j++) {
                    if (resultData[i].mcdId == ReplyresultData[j].DiscussionId) {
                        Str += '  <div class="replywraper"><div class="reply_pd"><div class="reply"><div class="info"><span class="name">' + ReplyresultData[j].aLinkName + '' + ReplyresultData[j].RoleName + '  回复  ' + ReplyresultData[j].aaLinkName + '' + ReplyresultData[j].arrRoleName + ' </span><span class="time">（' + ReplyresultData[j].CreateTime + '）</span></div><div class="cont">' + ReplyresultData[j].Content + '</div><div class="btn_box"><a class="btn_blu_m2" href="#t3" onclick="ReplyShow(' + resultData[i].mcdId + ',' + ReplyresultData[j].mcdrAdminId + ')" >回复</a>&nbsp;&nbsp;<a class="btn_blu_m2"  onclick="DeleteDiscussionReply(' + ReplyresultData[j].mcdrId + ',' + ReplyresultData[j].mcdrAdminId + ')" >删除</a></div></div></div></div>';
                    }
                }
            }
            Str += '<a class="readall" onclick=$(".onelist").css("display","")><b></b>浏览全部内容</a>';
        }
        else {
            Str += ' <div class="onelist"><div class="info"><span class="name"></span></div><div class="cont">暂无讨论</div><div class="btn_box"></div> </div>';
        }

        $("#DiscussionReply").append(Str);
    }, 2000)

}


//删除讨论
function DeleteDiscussion(id, aid) {
    var obj = {};
    obj.id = id;
    if (sessionStorage.getItem("AdminId") == aid || sessionStorage.getItem("AdminId") == 1) {
        if (confirm("确定删除吗")) {
            $.ajax({
                url: virualpath + '/Discussion/DeleteDiscussion',
                type: 'post',
                data: JSON.stringify(obj),
                async: true,
                dataType: 'json',
                contentType: 'application/json',
                success: function (data) {
                    if (data > 0) {
                        alert("删除成功")
                        location.reload();
                    } else {
                        alert('删除失败')
                    }
                }
            })
        }
    } else {
        alert("不可删除他人讨论内容！")
    }
}

//删除讨论回复
function DeleteDiscussionReply(id, aid) {
    if (sessionStorage.getItem("AdminId") == aid || sessionStorage.getItem("AdminId") == 1) {
        var obj = {};
        obj.id = id;
        if (confirm("确定删除吗")) {
            $.ajax({
                url: virualpath + '/Discussion/DeleteDiscussionReply',
                type: 'post',
                data: JSON.stringify(obj),
                async: true,
                dataType: 'json',
                contentType: 'application/json',
                success: function (data) {
                    if (data > 0) {
                        alert("删除成功")
                        location.reload();
                    } else {
                        alert('删除失败')
                    }
                }
            })
        }
    } else {
        alert("不可删除他人回复内容！")
    }
}


//获取材料列表
function GetTextBooks(id) {
    //var obj = {};
    //obj.id =  id;
    $.ajax({
        url: virualpath + '/Textbook/GetByIdTextbookInfo',
        type: 'get',
        data: { "id": "" + id + "" },
        async: true,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            var resultData = data;
            if (resultData != undefined) {
                var Pro_Textbooksstr = "";
                for (var i = 0; i < Object.keys(resultData).length; i++) {
                    Pro_Textbooksstr += ' <div class="onelist"><div class="pic" > <img src="' + resultData[i].Img + '" width="244" height="335" alt="" /></div ><div class="tit"><span class="font14 bold fray">' + resultData[i].TextName + '</span><br>' + resultData[i].TextAuthor + '<br>' + resultData[i].Publishing + '</div></div>'
                }
                $("#Pro_Textbooks").append(Pro_Textbooksstr);
            }
        }
    })
}

//获取书目列表
function GetBooks(id) {
    $.ajax({
        url: virualpath + '/Book/GetByIdBookInfo',
        type: 'get',
        data: { "id": "" + id + "" },
        async: true,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            var resultData = data
            if (resultData != undefined) {
                var Pro_Booksstr = "";
                for (var i = 0; i < Object.keys(resultData).length; i++) {
                    Pro_Booksstr += '<div class="onelist"><div class="pic" > <img src="' + resultData[i].Img + '" width="244" height="335" alt="" /></div ><div class="tit"><span class="font14 bold fray">' + resultData[i].BookName + '</span><br>' + resultData[i].BookAuthor + '<br>' + resultData[i].Publishing + '</div></div>'
                }

                $("#Pro_Books").append(Pro_Booksstr);
            }
        }
    })
}

//获取参考网站列表
function GetWebsites(id) {
    $.ajax({
        url: virualpath + '/Website/GetByIdWebsiteInfo',
        type: 'get',
        data: { "id": "" + id + "" },
        async: true,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            var resultData = data
            if (resultData != undefined) {
                var Pro_Websitesstr = "";
                for (var i = 0; i < Object.keys(resultData).length; i++) {
                    Pro_Websitesstr += ' <div class="onelist"><div class="pic" > <img src="' + resultData[i].Img + '" width="244" height="335" alt="" /></div ><div class="tit"><a href="' + resultData[i].WebUrl + '" target="_blank">' + resultData[i].WebUrl + '</a></div></div >'
                }
                $("#Pro_Websites").append(Pro_Websitesstr);
            }
        }
    })
}


//添加讨论内容
function InsertDiscussion() {
    var obj = {};
    obj.CourseId = prourlid;
    obj.Content = $("#DisContent").val();
    if (obj.Content == "") {
        alert("请输入讨论主题");
        return;
    }
    $.ajax({
        url: virualpath + '/Discussion/InsertDiscussion',
        type: 'post',
        data: JSON.stringify(obj),
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            if (data > 0) {
                alert('添加成功');
                UpCourseDisCount(prourlid)
                location.reload()
            } else {
                alert('添加失败')
            }
        }
    })
}

//修改课程讨论数量
function UpCourseDisCount(id) {
    var obj = {};
    obj.id = id;
    $.ajax({
        url: virualpath + '/Discussion/UpCourseDisCount',
        type: 'post',
        data: JSON.stringify(obj),
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            if (data > 0) {
                location.reload()
            } else {
            }
        }
    })
}

function ReplyShow(disId, raId) {
    $("#ReplyContent").css("display", "")
    sessionStorage.setItem("DisId", disId)
    sessionStorage.setItem("ReplyAdminId", raId)
}

//回复内容
function ReplyDiscussion() {
    var obj = {};
    obj.DiscussionId = sessionStorage.getItem("DisId");
    obj.ReplyAdminId = sessionStorage.getItem("ReplyAdminId");
    obj.Content = $("#Replytext").val();
    if (obj.Content == "") {
        alert("请输入回复内容");
        return;
    }
    $.ajax({
        url: virualpath + '/Discussion/ReplyDiscussion',
        type: 'post',
        data: JSON.stringify(obj),
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            if (data > 0) {
                alert('回复成功');
                location.reload()
            } else {
                alert('回复失败')
            }
        }
    })
}

function Show() {
    $('#hidder').css('display', '')
    $('#more').css('display', 'none')
}








function show() {
    popupDiv();
}
var aa = 0;
var dd = 0;
var ss = 0
var elevideo;
var cc = 0
function coursepaly() {
    //if (aa == 0) { 
    //    setTimeout(function () {
    //        aa = 1;
    //    var myVideo = document.getElementsByTagName('video')[0];
    //    myVideo.pause();
    //    var r = confirm("提交")
    //    if (r == true) {
    //        myVideo.play();
    //    }
    //    else {
    //        myVideo.pause();
    //    }
    //}, 5000);

    //}
    elevideo = document.getElementsByTagName('video')[0];
    if (aa == 0) {
        aa = 1;

        ss = elevideo.duration / 2;

        let timerId = setInterval(() => {
            /* alert('播放进度:' + parseFloat(elevideo.currentTime));*/
            dd = parseFloat(elevideo.currentTime);
            if (dd > ss) {
                // alert("一半了");
                elevideo.pause();
                clearInterval(timerId);//停止
                //elevideo.controls = false;
                // elevideo.load();
                if (cc == 0) {
                    layui.use('layer', function () {
                        cc = 1;
                        var layer = layui.layer;
                        layer.open({
                            type: 2 //此处以iframe举例。  ['../MLSMooc/ExamTkxzt.html?id=' + prourlid,'no']；  '../MLSMooc/ExamTkxzt.html?id=' + prourlid
                            , title: ''
                            , area: ['670px', '495px']
                            , shade: 0
                            , id: "yjk"
                            , shade: 0.1
                            , content: ['../MLSMooc/ExamTkxzt.html?id=' + prourlid, 'no']
                            //, maxmin: true
                            //, offset: 'auto'
                            //, btn: false
                            , yes: function () {
                                $(that).click();

                            }
                            , zIndex: layer.zIndex //重点1
                            , success: function (layero) {
                                var obj = $(layero).find("iframe")[0].contentWindow;//获取子页面向父页面传值；也可以是方法如obj.xxx();
                               
                                if (obj.flag == 0) {
                                 
                                    $('.layui-layer').height('325px');//改变弹出框的高度；
                                }
                                if (obj.flag == 1) {
                                    $('.layui-layer').height('495px');
                                }
                              
                                layer.setTop(layero); //重点2
                            }
                        });

                    });
                      $("#yjk").next().hide();//隐藏弹框右上角关闭
                }




            }
        }, 1000);
        if (aa = 1 && dd > ss) {
            if (elevideo.paused == true) {
                elevideo.pause();
            }
        }

    }
}


function playPause(id) {
    if (id == 0) {
        var myVideo = document.getElementsByTagName('video')[id];
        if (myVideo.paused) {
            myVideo.play();

            $('#playTips').removeClass('playTips').addClass('playTips2').fadeOut();

        }
        else {

            myVideo.pause();
            $('#playTips').removeClass('playTips2').addClass('playTips').fadeIn();
        }
    }
    else {
        var myVideo = document.getElementsByTagName('video')[id];
        if (myVideo.paused) {
            myVideo.play();
            $('#playTip_p').removeClass('playTip_p').addClass('playTip2_p').fadeOut();
        }
        else {
            myVideo.pause();
            $('#playTip_p').removeClass('playTip2_p').addClass('playTip_p').fadeIn();
        }
    }
}
window.document.oncontextmenu = function () {
    //alert('请不要点击鼠标右键！');
    return false;
}


function popupDiv() {
    var myVideo = document.getElementsByTagName('video')[0];
    myVideo.pause();
    $('#playTips').removeClass('playTips2').addClass('playTips').fadeIn();

    var div_obj = $("#pop_div");
    //窗口宽度,高度
    var winWidth = $(window).width();
    var winHeight = $(window).height();
    //弹出的div的宽度,高度
    var popHeight = div_obj.height();
    var popWidth = div_obj.width();
    div_obj.animate({ opacity: "show", left: (winWidth - popWidth) / 2, top: (winHeight - popHeight) / 2, width: popWidth, height: popHeight }, 300);
    $("#mask").show();
}
function hideDiv() {

    var myVideo = document.getElementsByTagName('video')[1];
    myVideo.pause();
    $('#playTip_p').removeClass('playTip2_p').addClass('playTip_p').fadeIn();


    $("#pop_div").animate({ opacity: "hide" }, 300);
    $("#mask").hide();
}






//点击弹框选择题模态窗
function updateTkxzt(id) {
    layer.open({
        type: 2 //此处以iframe举例
        , title: '编辑弹框选择题'
        , area: ['720px', '770px']
        , shade: 0
        , maxmin: false
        , offset: 'auto'
        , content: ['upload-knowledge-points.html?/id=' + id, 'no']
        , btn: false
        , yes: function () {
            $(that).click();
        }
        , zIndex: layer.zIndex //重点1
        , success: function (layero) {
            layer.setTop(layero); //重点2
        }
    });
}




